package core

import (
	"context"
	"fmt"
	"framework-server/global"
	"framework-server/initialize"
	"github.com/go-kit/log/level"
	"os"
	"os/signal"
	"strconv"
	"syscall"
	"time"
)

type server interface {
	ListenAndServe() error
	Shutdown(context context.Context) error
}

func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

func RunWindowsServer() {
	Router := initialize.Routers()
	Router.Static("/form-generator", "./resource/page")

	address := fmt.Sprintf(":%d", global.GVA_CONFIG.System.Addr)
	s := initServer(address, Router)
	// 保证文本顺序输出
	// In order to ensure that the text order output can be deleted
	time.Sleep(10 * time.Microsecond)
	filename := "./app.pid"

	if exist, _ := PathExists(filename); !exist {
		f, err := os.Create(filename)
		defer f.Close()
		if err != nil {
			level.Error(global.GVA_LOG).Log("err", err.Error())
			return
		}
	}

	f, err := os.OpenFile(filename, os.O_WRONLY|os.O_TRUNC, 0644)
	defer f.Close()
	if err != nil {
		level.Error(global.GVA_LOG).Log("err", err.Error())
		return
	} else {
		_, err = f.Write([]byte(strconv.Itoa(syscall.Getpid()) + "\n"))
	}
	level.Info(global.GVA_LOG).Log("msg", "server run success on "+address)

	fmt.Printf(`欢迎使用 Gin-Vue-Admin
	默认自动化文档地址:http://127.0.0.1%s/swagger/index.html
	默认前端文件运行地址:http://127.0.0.1:8000
`, address)

	go func() {
		level.Error(global.GVA_LOG).Log("err", s.ListenAndServe().Error())
	}()

	quit := make(chan os.Signal)
	signal.Notify(quit, os.Interrupt, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
	<-quit
	level.Info(global.GVA_LOG).Log("msg", "Shutdown Server ...")
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := s.Shutdown(ctx); err != nil {
		level.Error(global.GVA_LOG).Log("msg", fmt.Sprintf("Server Shutdown: %s", err))
		return
	}
	level.Info(global.GVA_LOG).Log("msg", "Server exiting")
}
